<template>
    <view class="container">
        <!-- 页面标题 -->
        <view class="page-header">
            <view class="header-content">
                <text class="page-title">节点ID管理</text>
                <text class="page-subtitle">管理设备节点ID配置</text>
            </view>
        </view>

        <!-- 当前选择的节点 -->
        <view class="current-node-card">
            <view class="card-header">
                <view class="card-icon">
                    <text class="icon-text">🎯</text>
                </view>
                <text class="card-title">当前选择节点</text>
            </view>
            <view class="card-content">
                <view class="current-node-info">
                    <text class="node-label">节点ID:</text>
                    <text class="node-value">{{selectedNodeId || '未选择'}}</text>
                </view>
            </view>
        </view>

        <!-- 节点选择器 -->
        <view class="selector-card">
            <view class="card-header">
                <view class="card-icon">
                    <text class="icon-text">📋</text>
                </view>
                <text class="card-title">选择节点</text>
            </view>
            <view class="card-content">
                <picker @change="onNodeIdChange" :value="nodeIdIndex" :range="nodeIdOptions" mode="selector">
                    <view class="node-selector">
                        <text class="selector-text">{{nodeIdOptions[nodeIdIndex] || '请选择节点ID'}}</text>
                        <text class="selector-arrow">▼</text>
                    </view>
                </picker>
            </view>
        </view>

        <!-- 自定义节点管理 -->
        <view class="manage-card">
            <view class="card-header">
                <view class="card-icon">
                    <text class="icon-text">⚙️</text>
                </view>
                <text class="card-title">自定义节点管理</text>
            </view>
            <view class="card-content">
                <!-- 添加节点区域 -->
                <view class="add-section">
                    <view class="section-title">
                        <text class="title-text">添加新节点</text>
                    </view>
                    <view class="input-container">
                        <input 
                            class="node-input" 
                            v-model="newNodeId" 
                            placeholder="请输入新的节点ID" 
                            maxlength="20"
                        />
                        <button class="add-btn" @click="addCustomNode">
                            <view class="btn-content">
                                <text class="btn-icon">➕</text>
                                <text class="btn-text">添加</text>
                            </view>
                        </button>
                    </view>
                </view>

                <!-- 节点列表 -->
                <view class="nodes-section">
                    <view class="section-title">
                        <text class="title-text">节点列表</text>
                        <text class="count-text">({{nodeIdOptions.length}}个)</text>
                    </view>
                    <view class="nodes-list">
                        <view class="node-item" v-for="(nodeId, index) in nodeIdOptions" :key="index">
                            <view class="node-info">
                                <view class="node-icon">
                                    <text class="icon-text">{{isDefaultNode(nodeId) ? '🔒' : '🏷️'}}</text>
                                </view>
                                <view class="node-details">
                                    <!-- 编辑模式 -->
                                    <view v-if="isEditing && editingNodeId === nodeId" class="edit-container">
                                        <input 
                                            class="edit-input" 
                                            v-model="editingNodeName" 
                                            placeholder="请输入节点名称"
                                            maxlength="20"
                                        />
                                        <view class="edit-actions">
                                            <button class="save-edit-btn" @click="saveEdit">
                                                <text class="btn-text">保存</text>
                                            </button>
                                            <button class="cancel-edit-btn" @click="cancelEdit">
                                                <text class="btn-text">取消</text>
                                            </button>
                                        </view>
                                    </view>
                                    <!-- 正常显示模式 -->
                                    <view v-else>
                                        <text class="node-name">{{nodeId}}</text>
                                        <text class="node-type">{{isDefaultNode(nodeId) ? '系统默认' : '自定义节点'}}</text>
                                    </view>
                                </view>
                            </view>
                            <view class="node-actions" v-if="!isEditing || editingNodeId !== nodeId">
                                <button 
                                    class="select-btn" 
                                    :class="{active: selectedNodeId === nodeId}"
                                    @click="selectNode(nodeId, index)"
                                >
                                    <text class="btn-text">{{selectedNodeId === nodeId ? '已选择' : '选择'}}</text>
                                </button>
                                <button 
                                    class="edit-btn" 
                                    v-if="!isDefaultNode(nodeId)"
                                    @click="startEditNode(nodeId)"
                                >
                                    <text class="btn-text">编辑</text>
                                </button>
                                <button 
                                    class="delete-btn" 
                                    v-if="!isDefaultNode(nodeId)"
                                    @click="removeCustomNode(nodeId)"
                                >
                                    <text class="btn-text">删除</text>
                                </button>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>

        <!-- 底部操作区域 -->
        <view class="bottom-actions">
            <button class="action-btn back-btn" @click="goBack">
                <view class="btn-content">
                    <text class="btn-icon">⬅️</text>
                    <text class="btn-text">返回</text>
                </view>
            </button>
            <button class="action-btn save-btn" @click="saveAndReturn">
                <view class="btn-content">
                    <text class="btn-icon">💾</text>
                    <text class="btn-text">保存并返回</text>
                </view>
            </button>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            // 选择的节点ID
            selectedNodeId: '',
            // 新节点ID输入
            newNodeId: '',
            // 可选择的节点ID列表
            nodeIdOptions: ['1', '2', '3', '4', 'central'],
            // 节点ID选择器的索引
            nodeIdIndex: 0,
            // 默认节点列表
            defaultNodes: ['1', '2', '3', '4', 'central'],
            // 编辑状态
            editingNodeId: '',
            editingNodeName: '',
            isEditing: false
        }
    },
    onLoad(options) {
        // 从参数中获取当前选择的节点ID
        if (options.selectedNodeId) {
            this.selectedNodeId = options.selectedNodeId;
            this.nodeIdIndex = this.nodeIdOptions.indexOf(options.selectedNodeId);
        }
        // 加载自定义节点
        this.loadCustomNodes();
    },
    methods: {
        // 节点ID选择器变化
        onNodeIdChange(e) {
            this.nodeIdIndex = e.detail.value;
            this.selectedNodeId = this.nodeIdOptions[this.nodeIdIndex];
        },
        
        // 选择节点
        selectNode(nodeId, index) {
            this.selectedNodeId = nodeId;
            this.nodeIdIndex = index;
        },
        
        // 判断是否为默认节点
        isDefaultNode(nodeId) {
            return this.defaultNodes.includes(nodeId);
        },
        
        // 添加自定义节点
        addCustomNode() {
            const nodeId = this.newNodeId.trim();
            
            // 输入验证
            if (!nodeId) {
                uni.showToast({
                    title: '请输入节点ID',
                    icon: 'none'
                });
                return;
            }
            
            // 检查是否已存在
            if (this.nodeIdOptions.includes(nodeId)) {
                uni.showToast({
                    title: '节点ID已存在',
                    icon: 'none'
                });
                return;
            }
            
            // 添加到选项列表
            this.nodeIdOptions.push(nodeId);
            
            // 保存到本地存储
            this.saveCustomNodes();
            
            // 清空输入框
            this.newNodeId = '';
            
            uni.showToast({
                title: '添加成功',
                icon: 'success'
            });
        },
        
        // 删除自定义节点
        removeCustomNode(nodeId) {
            // 不能删除默认节点
            if (this.isDefaultNode(nodeId)) {
                uni.showToast({
                    title: '不能删除默认节点',
                    icon: 'none'
                });
                return;
            }
            
            uni.showModal({
                title: '确认删除',
                content: `确定要删除节点 "${nodeId}" 吗？`,
                success: (res) => {
                    if (res.confirm) {
                        // 从选项列表中移除
                        const index = this.nodeIdOptions.indexOf(nodeId);
                        if (index > -1) {
                            this.nodeIdOptions.splice(index, 1);
                        }
                        
                        // 如果删除的是当前选择的节点，重置选择
                        if (this.selectedNodeId === nodeId) {
                            this.selectedNodeId = this.nodeIdOptions[0] || '';
                            this.nodeIdIndex = 0;
                        } else {
                            // 更新索引
                            this.nodeIdIndex = this.nodeIdOptions.indexOf(this.selectedNodeId);
                        }
                        
                        // 保存到本地存储
                        this.saveCustomNodes();
                        
                        uni.showToast({
                            title: '删除成功',
                            icon: 'success'
                        });
                    }
                }
            });
        },
        
        // 获取自定义节点列表（排除默认节点）
        getCustomNodes() {
            return this.nodeIdOptions.filter(nodeId => !this.defaultNodes.includes(nodeId));
        },
        
        // 保存自定义节点到本地存储
        saveCustomNodes() {
            try {
                const customNodes = this.getCustomNodes();
                uni.setStorageSync('customNodes', customNodes);
            } catch (e) {
                console.error('保存自定义节点失败:', e);
            }
        },
        
        // 从本地存储加载自定义节点
        loadCustomNodes() {
            try {
                const customNodes = uni.getStorageSync('customNodes') || [];
                // 将自定义节点添加到选项列表（避免重复）
                customNodes.forEach(nodeId => {
                    if (!this.nodeIdOptions.includes(nodeId)) {
                        this.nodeIdOptions.push(nodeId);
                    }
                });
            } catch (e) {
                console.error('加载自定义节点失败:', e);
            }
        },
        
        // 返回上一页
        goBack() {
            uni.navigateBack();
        },
        
        // 开始编辑节点
        startEditNode(nodeId) {
            if (this.isDefaultNode(nodeId)) {
                uni.showToast({
                    title: '系统默认节点不能编辑',
                    icon: 'none'
                });
                return;
            }
            this.editingNodeId = nodeId;
            this.editingNodeName = nodeId;
            this.isEditing = true;
        },
        
        // 取消编辑
        cancelEdit() {
            this.editingNodeId = '';
            this.editingNodeName = '';
            this.isEditing = false;
        },
        
        // 保存编辑
        saveEdit() {
            const newName = this.editingNodeName.trim();
            
            // 输入验证
            if (!newName) {
                uni.showToast({
                    title: '请输入节点名称',
                    icon: 'none'
                });
                return;
            }
            
            // 检查是否与其他节点重复
            if (newName !== this.editingNodeId && this.nodeIdOptions.includes(newName)) {
                uni.showToast({
                    title: '节点ID已存在',
                    icon: 'none'
                });
                return;
            }
            
            // 更新节点列表
            const index = this.nodeIdOptions.indexOf(this.editingNodeId);
            if (index > -1) {
                this.nodeIdOptions.splice(index, 1, newName);
            }
            
            // 如果编辑的是当前选择的节点，更新选择
            if (this.selectedNodeId === this.editingNodeId) {
                this.selectedNodeId = newName;
            }
            
            // 保存到本地存储
            this.saveCustomNodes();
            
            // 重置编辑状态
            this.cancelEdit();
            
            uni.showToast({
                title: '修改成功',
                icon: 'success'
            });
        },
        
        // 保存并返回
        saveAndReturn() {
            // 保存当前选择到全局存储
            try {
                uni.setStorageSync('selectedNodeId', this.selectedNodeId);
                uni.setStorageSync('nodeIdIndex', this.nodeIdIndex);
                
                // 保存自定义节点
                this.saveCustomNodes();
                
                uni.showToast({
                    title: '保存成功',
                    icon: 'success'
                });
                
                // 延迟返回，让用户看到成功提示
                setTimeout(() => {
                    uni.navigateBack();
                }, 1000);
            } catch (e) {
                console.error('保存失败:', e);
                uni.showToast({
                    title: '保存失败',
                    icon: 'none'
                });
            }
        }
    }
}
</script>

<style scoped>
.container {
    min-height: 100vh;
    background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
    padding: 20rpx;
}

/* 页面标题 */
.page-header {
    background: rgba(30, 30, 50, 0.95);
    border-radius: 20rpx;
    padding: 40rpx 30rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.3);
    border: 1rpx solid rgba(255, 255, 255, 0.1);
}

.header-content {
    text-align: center;
}

.page-title {
    font-size: 48rpx;
    font-weight: bold;
    color: #ffffff;
    display: block;
    margin-bottom: 10rpx;
}

.page-subtitle {
    font-size: 28rpx;
    color: #b0b0b0;
    display: block;
}

/* 卡片通用样式 */
.current-node-card,
.selector-card,
.manage-card {
    background: rgba(40, 40, 60, 0.95);
    border-radius: 20rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.3);
    border: 1rpx solid rgba(255, 255, 255, 0.1);
    overflow: hidden;
}

.card-header {
    display: flex;
    align-items: center;
    padding: 30rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
}

.card-icon {
    width: 60rpx;
    height: 60rpx;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.2);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 20rpx;
}

.icon-text {
    font-size: 32rpx;
}

.card-title {
    font-size: 32rpx;
    font-weight: bold;
}

.card-content {
    padding: 30rpx;
}

/* 当前节点信息 */
.current-node-info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx;
    background: rgba(60, 60, 80, 0.8);
    border-radius: 12rpx;
    border-left: 6rpx solid #667eea;
}

.node-label {
    font-size: 28rpx;
    color: #b0b0b0;
}

.node-value {
    font-size: 32rpx;
    font-weight: bold;
    color: #ffffff;
}

/* 节点选择器 */
.node-selector {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 25rpx 30rpx;
    background: rgba(60, 60, 80, 0.8);
    border-radius: 12rpx;
    border: 2rpx solid rgba(255, 255, 255, 0.2);
    transition: all 0.3s ease;
}

.node-selector:active {
    background: rgba(80, 80, 100, 0.8);
    transform: scale(0.98);
}

.selector-text {
    font-size: 30rpx;
    color: #ffffff;
}

.selector-arrow {
    font-size: 24rpx;
    color: #b0b0b0;
}

/* 管理区域 */
.add-section,
.nodes-section {
    margin-bottom: 40rpx;
}

.section-title {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
}

.title-text {
    font-size: 30rpx;
    font-weight: bold;
    color: #ffffff;
}

.count-text {
    font-size: 24rpx;
    color: #b0b0b0;
    margin-left: 10rpx;
}

/* 输入容器 */
.input-container {
    display: flex;
    gap: 20rpx;
}

.node-input {
    flex: 1;
    padding: 25rpx 30rpx;
    background: rgba(60, 60, 80, 0.8);
    border: 2rpx solid rgba(255, 255, 255, 0.2);
    border-radius: 12rpx;
    font-size: 28rpx;
    color: #ffffff;
}

.node-input:focus {
    border-color: #667eea;
    background: rgba(80, 80, 100, 0.8);
}

.add-btn {
    padding: 25rpx 40rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border: none;
    border-radius: 12rpx;
    font-size: 28rpx;
    display: flex;
    align-items: center;
    gap: 10rpx;
    transition: all 0.3s ease;
}

.add-btn:active {
    transform: scale(0.95);
}

/* 节点列表 */
.nodes-list {
    display: flex;
    flex-direction: column;
    gap: 15rpx;
}

.node-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 25rpx;
    background: rgba(60, 60, 80, 0.6);
    border-radius: 12rpx;
    border: 2rpx solid rgba(255, 255, 255, 0.1);
    transition: all 0.3s ease;
}

.node-item:hover {
    background: rgba(80, 80, 100, 0.8);
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.3);
}

.node-info {
    display: flex;
    align-items: center;
    gap: 20rpx;
}

.node-icon {
    width: 50rpx;
    height: 50rpx;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
    display: flex;
    align-items: center;
    justify-content: center;
}

.node-details {
    display: flex;
    flex-direction: column;
}

.node-name {
    font-size: 30rpx;
    font-weight: bold;
    color: #ffffff;
    margin-bottom: 5rpx;
}

.node-type {
    font-size: 24rpx;
    color: #b0b0b0;
}

.node-actions {
    display: flex;
    gap: 15rpx;
}

.select-btn,
.edit-btn,
.delete-btn {
    padding: 15rpx 25rpx;
    border: none;
    border-radius: 8rpx;
    font-size: 24rpx;
    transition: all 0.3s ease;
}

.select-btn {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
}

.select-btn.active {
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    color: white;
}

.edit-btn {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    color: white;
}

.delete-btn {
    background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
    color: white;
}

.save-edit-btn {
    padding: 15rpx 25rpx;
    background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%);
    color: white;
    border: none;
    border-radius: 8rpx;
    font-size: 24rpx;
    margin-right: 15rpx;
}

.cancel-edit-btn {
    padding: 15rpx 25rpx;
    background: linear-gradient(135deg, #95a5a6 0%, #7f8c8d 100%);
    color: white;
    border: none;
    border-radius: 8rpx;
    font-size: 24rpx;
}

.edit-container {
    display: flex;
    flex-direction: column;
    gap: 15rpx;
}

.edit-input {
    padding: 20rpx;
    background: rgba(60, 60, 80, 0.8);
    border: 2rpx solid rgba(255, 255, 255, 0.2);
    border-radius: 8rpx;
    font-size: 28rpx;
    color: #ffffff;
}

.edit-actions {
    display: flex;
    gap: 15rpx;
}

.select-btn:active,
.delete-btn:active {
    transform: scale(0.95);
}

/* 底部操作区域 */
.bottom-actions {
    display: flex;
    gap: 20rpx;
    padding: 30rpx 0;
}

.action-btn {
    flex: 1;
    padding: 30rpx;
    border: none;
    border-radius: 15rpx;
    font-size: 30rpx;
    font-weight: bold;
    transition: all 0.3s ease;
}

.back-btn {
    background: linear-gradient(135deg, #95a5a6 0%, #7f8c8d 100%);
    color: white;
}

.save-btn {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
}

.action-btn:active {
    transform: scale(0.95);
}

.btn-content {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10rpx;
}

.btn-icon {
    font-size: 28rpx;
}

.btn-text {
    font-size: 28rpx;
}
</style>